package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.feign.workable.entity.BindTaskIdRequest;
import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 拒绝任务监听器
 *
 * @author lichong
 * @since 2023/6/15 17:09
 */
@Slf4j
@Component("bindTaskToBusinessListener")
public class BindTaskToBusinessListener implements TaskListener {

    @Resource
    private TaskService taskService;

    @Resource
    private HistoryService historyService;

    @Resource
    private HttpUtil httpUtil;

    @Value("${approval.bind.url}")
    private String bindTaskToBusinessCallBackUrl;

    @Override
    public void notify(DelegateTask delegateTask) {
        Map<String, Object> variables = delegateTask.getVariables();
        Object childVariable = variables.get("childVariable");
        Map<String, Object> variablesLocal = taskService.getVariablesLocal(delegateTask.getId());
        variablesLocal.put("childVariable",childVariable);
        taskService.setVariablesLocal(delegateTask.getId(),variablesLocal);
        log.info("执行任务id与业务主键绑定监听器");
        String processInstanceId = delegateTask.getProcessInstanceId();
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(historicProcessInstance!=null){
            String businessKey = historicProcessInstance.getBusinessKey();
            BindTaskIdRequest bindTaskIdRequest = new BindTaskIdRequest();
            bindTaskIdRequest.setTaskId(delegateTask.getId());
            bindTaskIdRequest.setBusinessKey(businessKey);
            bindTaskIdRequest.setProcessDefinitionKey(historicProcessInstance.getProcessDefinitionKey());
            log.info("sento-workspace：{}，参数{}",bindTaskToBusinessCallBackUrl,bindTaskIdRequest);
            httpUtil.post(bindTaskToBusinessCallBackUrl,bindTaskIdRequest);
        }
    }
}
